<template>
  <div>
    <h1>登录画面</h1>
    <el-form :model="form" label-width="auto" style="max-width: 600px">
      <el-form-item label="用户名">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()
const form = ref({
  userName: '',
  password: ''
})

// 假设这是登录成功后的处理逻辑
const loginSuccess = (response) => {
  localStorage.setItem('userId', response.userId);
  // 其他登录成功后的操作
};
const onLogin = async () => {
  try {
    const response = await service.post('/user/login', null, {
      params: form.value,
    });

    console.log('登录响应:', response);

    if (response.success) {
      // 保存用户信息
      localStorage.setItem('token', String(response.user.id));
      localStorage.setItem('userType', String(response.user.useType));
      localStorage.setItem('deptID', String(response.user.deptID));
      localStorage.setItem('realName', response.user.realName);
      
      // 如果是医生，存储doctorId
      if (String(response.user.useType) === '3') { // 假设3是医生类型
        localStorage.setItem('doctorId', String(response.user.id));
      }

      ElMessage.success('登录成功');
      router.push('/'); // 确保跳转到主页面
    } else {
      ElMessage.error(response.message);
    }
  } catch (error) {
    console.error('登录失败', error);
    ElMessage.error('登录失败，请检查网络连接');
  }
};
</script>